//
//  CCCityViewModel.m
//  Party
//
//  Created by its on 15/3/16.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCCityViewModel.h"
#import "CCCityModel.h"
#import <LinqToObjectiveC/NSDictionary+LinqExtensions.h>
#import <LinqToObjectiveC/NSArray+LinqExtensions.h>

@interface CCCityViewModel()
@property(nonatomic, strong) CCCityModel *model;
@end
@implementation CCCityViewModel

- (id) initWithModel:(CCCityModel *)model {
  if (self = [super init]) {
    _model = model;
    _finishSignal = [[RACSubject subject] setNameWithFormat:@"CCCityViewModel finishSignal"];
    [_model.searchSignal subscribeNext:^(NSDictionary *x) {
      
      _searchArray = [[[x allKeys] linq_sort] linq_select:^id(id item) {
        if ([item isEqualToString:@"?"]) return @"定位城市";
        if ([item isEqualToString:@"@"]) return @"热门城市";
        return item;
      }];
      NSMutableDictionary *dic = [NSMutableDictionary dictionary];
      _searchResultDic = [x linq_where:^BOOL(id key, id value) {
        if ([key isEqualToString:@"?"]) {
          dic[@"定位城市"] = value;
          return NO;
        }
        if ([key isEqualToString:@"@"]) {
          dic[@"热门城市"] = value;
          return NO;
        }
        return YES;
      }];
      _searchResultDic = [_searchResultDic linq_Merge:dic];
      [_finishSignal sendNext:nil];
    } error:^(NSError *error) {
      [_finishSignal sendError: error];
    }
     ];
  }
  return self;
}

- (void) setViewDidLoadSignal:(RACSignal *)viewDidLoadSignal {
  [_model.findAllSignal subscribeNext:^(RACTuple *x) {
    self.searchArray = x.first;
    self.searchArray = [self.searchArray linq_select:^id(id item) {
      if ([item isEqualToString:@"?"]) return @"定位城市";
      if ([item isEqualToString:@"@"]) return @"热门城市";
      return item;
    }];
    self.searchResultDic = x.second;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    self.searchResultDic = [self.searchResultDic linq_where:^BOOL(id key, id value) {
      if ([key isEqualToString:@"?"]) {
        dic[@"定位城市"] = value;
        return NO;
      }
      if ([key isEqualToString:@"@"]) {
        dic[@"热门城市"] = value;
        return NO;
      }
      return YES;
    }];
    self.searchResultDic = [self.searchResultDic linq_Merge:dic];
    [_finishSignal sendNext:nil];
  } error:^(NSError *error) {
    [self.finishSignal sendError:error];
  }];
}

- (void) beginSearch {
  [_model searchWithString:@""];
}
- (void) searchWithString:(NSString *)string {
  [_model searchWithString: string];
}
- (void) endSearch {
  
}

@end
